// 打包后处理文件夹
const fs = require("fs");
const path = require("path");
const npmArg = process.argv.slice(2);
// 参数1：目标文件夹
// 参数2：目标文件（可选字符串、数组）
const targetFile = npmArg[0].includes(",") ? npmArg[0].split(",").filter(item => item) : npmArg[0];
const targetDir = npmArg[1] || "/dist";
if (!targetFile) {
  console.log("请输入需要删除的文件以及文件夹,以逗号隔开");
  return;
}

function showTips(err, filePath) {
  const status = err ? "失败" : "成功";
  console.log(filePath + "删除" + status);
  if (err) {
    console.log(err + "\n" + "filePath");
  }
}

function removeDirByNames(fileList, targetName) {
  const removeSingleFile = (fileName) => {
    if (fileList.includes(fileName)) {
      const filePath = path.join(__dirname, targetDir, "/", fileName);
      fs.stat(filePath, (err, info) => {
        if (info.isDirectory()) {
          fs.rm(filePath, { recursive: true, force: true }, (err) => {
            showTips(err, filePath);
          });
        } else {
          fs.unlink(filePath, (err) => {
            showTips(err, filePath);
          });
        }
      });
    }
  };
  if (typeof targetName === "string") {
    removeSingleFile(targetName);
  }
  if (typeof targetName === "object") {
    console.log(targetName);
    targetName.forEach((singleName) => {
      removeSingleFile(singleName);
    });
  }
}

fs.readdir(path.join(__dirname, targetDir), "utf-8", (err, file) => {
  if (!err) {
    try {
      removeDirByNames(file, targetFile);
    } catch (e) {
      console.log(e);
    }
  }
});

